Checked and Unchecked Exception
C# allows you to specify whether your code will raise an exception when overflow occurs by using the keywords checked and unchecked. To specify that an expression be checked for overflow, use checked. To specify that overflow be ignored, use unchecked. In this case, the result is truncated to fit into the target type of the expression.
The checked and unchecked keywords has these two general forms:
checked (expr)
checked
{
// statements to be checked
}
unchecked (expr)
unchecked
{
// statements for which overfl ow is ignored
}
Program on checked and unchecked.
using System;
class vision
{
public static void Main()
{
byte a, b;
byte result;
a = 127;
b = 127;
try
{
result = unchecked((byte)(a * b));
Console.WriteLine("Unchecked result: " + result);
result = checked((byte)(a * b)); // this causes exception
Console.WriteLine("Checked result: " + result); // won't execute
}
catch (OverflowException exc)
{
Console.WriteLine(exc);
}
}
}
Program on checked and unchecked statement blocks
using System;
class vision
{
public static void Main()
{
byte a, b;
byte result;
a = 127;
b = 127;
try
{
unchecked
{
a = 127;
b = 127;
result = unchecked((byte)(a * b));
Console.WriteLine("Unchecked result: " + result);
a = 125;
b = 5;
result = unchecked((byte)(a * b));
Console.WriteLine("Unchecked result: " + result);
}
checked
{
a = 2;
b = 7;
result = checked((byte)(a * b)); // this is OK
Console.WriteLine("Checked result: " + result);
a = 127;
b = 127;
result = checked((byte)(a * b)); // this causes exception
Console.WriteLine("Checked result: " + result); // won't execute
}
}
catch (OverflowException exc)
{
Console.WriteLine(exc);
}
}
}